/* eslint-disable vue/valid-v-for */
<template>
  <div class="app-container">
    <!--搜索条件-->
    <div class="filter-container">
      <el-row :gutter="13" type="flex">
        <el-col :span="2">
          <el-select v-model="selectStatusValue" placeholder="请选择" @change="selectStatus">
            <el-option
              v-for="item in statusList"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-col>

        <el-col :span="2">
          <el-select v-model="selectWarehouseValue" placeholder="请选择" @change="selectWarehouseValues">
            <el-option
              v-for="item in warehouseList"
              :key="item.warehouseId"
              :label="item.warehouseName"
              :value="item.warehouseId"
            />
          </el-select>
        </el-col>

        <el-col :span="6">
          <el-date-picker
            v-model="createTimeInterval"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
          />
        </el-col>

        <!-- @blur="searchSku" -->
        <el-col :span="4">
          <el-input v-model="search" placeholder="输入供应商.sku查询"/>
        </el-col>

        <el-col :span="1">
          <el-button type="primary" @click="searchSku">查询</el-button>
        </el-col>

        <el-col :span="1">
          <el-button v-show="checkPermission('pas:purchase:receipt')" type="primary" @click="addFun()">收货</el-button>
        </el-col>
      </el-row>
    </div>

    <!-- v-loading="listLoading" -->
    <div class="table-ymm">
      <el-table
        :data="purchaseItemList"
        border
        highlight-current-row
        style="width: 95%;"
        height="450"
        @selection-change="handleSelectionChange"
      >
        <el-table-column :selectable="isRowDisable" type="selection" width="50"/>
        <el-table-column prop="supplier" label="供应商" width="250"/>
        <el-table-column prop="warehouseName" label="收货仓" width="80"/>
        <el-table-column prop="skuCode" label="SKU编码" width="120"/>
        <el-table-column prop="skuName" label="SKU名称" width="350"/>
        <!-- <el-table-column :formatter="formatterStatus" prop="status" label="状态" min-width="5%"/> -->

        <el-table-column prop="status" label="采购状态" width="100">
          <template slot-scope="scope">
            <span v-if="scope.row.status==1" style="color:#28A087">待采购</span>
            <span v-else-if="scope.row.status==2" style="color:#F05050">采购中</span>
            <span v-else-if="scope.row.status==3">已完成</span>
            <span v-else-if="scope.row.status==4">已驳回</span>
            <span v-else-if="scope.row.status==5">已取消</span>
          </template>
        </el-table-column>

        <el-table-column prop="amount" label="采购数量" width="100"/>
        <el-table-column prop="collectAmount" label="实际收货量" width="100"/>
        <el-table-column prop="status" label="退货数量" width="100">
          <template slot-scope="scope">
            <span v-if="scope.row.returnAmount===null" style="color:#28A087">0</span>
            <span v-else-if="scope.row.returnAmount !== null" style="color:#F05050">{{ scope.row.returnAmount }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="purchaseNumber" label="采购单号" width="150"/>
        <el-table-column label="操作" width="150">
          <template slot-scope="scope">
            <el-button v-show="checkPermission('pas:purchase:returngoods')" v-if="(scope.row.delivery === 2 && scope.row.status ===2) || (scope.row.delivery === 2 && scope.row.status ===3)" type="button" @click="open(scope.row)">采购退货</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!--分页-->
    <div class="pagination-container">
      <el-pagination
        v-show="total>0"
        :current-page="listQuery.page"
        :page-sizes="[30,50,100,500]"
        :page-size="listQuery.pageSize"
        :total="total"
        background
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <component
      :is="modal"
      :modal-data="modalData"
      :modal-static-data="{closeChildAndRefresh}"
      @close="closeChild"
    />
  </div>
</template>

<script>
// post
import { get } from '@/api/utils'
import Received from './dialog/Received.vue'
import { message } from '@/utils/utils'
// import { parseTime } from '@/utils/index'
import { distributorList } from '@/api/payment'
import { getUserInfo } from '@/api/login'

// import { parseTime } from '@/utils'

export default {
  data() {
    return {
      modal: null,
      modalData: {},
      warehouseList: [],
      purchaseItemList: [],
      selectWarehouseValue: null,
      statusList: [
        { value: '1', label: '待采购' },
        { value: '2', label: '采购中' },
        { value: '3', label: '已完成' },
        { value: '4', label: '已驳回' },
        { value: '5', label: '已取消' }
      ],
      selectSortValue: null,
      selectStatusValue: null,
      createTimeInterval: '',
      search: '',
      selectName: '请选择',
      dialogFormVisible: false,
      skuList: [],
      total: 1,
      listLoading: true,
      offset: 0,
      limit: 30,
      listQuery: {
        page: 1,
        pageSize: 30,
        keyword: null,
        starTime: null,
        endTime: null,
        shipmentNo: null,
        time: null,
        pageNumber: null
      },
      supplierList: [],
      lianbaoBrandList: [],
      masterCategoryList: [],
      selectPurchaseItemList: []
    }
  },
  created() {
    this.getPurchaseItemist()
    this.getWarehouseList()
    this.getPermission()
  },

  methods: {
    open(row) {
      this.$prompt('请输入退货数量', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputPattern: /(^[1-9]\d*$)/,
        inputErrorMessage: '请输入正整数'
      }).then(({ value }) => {
        if (row.collectAmount !== 0 && value > row.collectAmount) {
          this.$message({ type: 'info', message: '退货数量不能大于收货数量！' })
          return
        }
        if (row.collectAmount === 0 && value > row.amount) {
          this.$message({ type: 'info', message: '退货数量不能大于采购数量！' })
          return
        }
        var data = { 'purchaseItemId': row.purchaseItemId, 'amount': value }
        get('/wxh-cloud-rest/rest/', '/pas/purchaseItem/returnGoods', data)
          .then(response => {
            this.$message({
              type: 'info',
              message: response.data.messge
            })
            this.getPurchaseItemist()
          })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '取消输入'
        })
      })
    },
    formatterClassification(row, column) {
      if (row.classification) {
        if (row.classification === 1) {
          return '整机'
        } else if (row.classification === 2) {
          return '工具'
        } else if (row.classification === 3) {
          return '辅材'
        } else if (row.classification === 4) {
          return '赠品'
        }
      }
    },
    formatterStatus(row, column) {
      if (row.status) {
        if (row.status === 1) {
          return '正常'
        } else if (row.status === 2) {
          return '停采'
        } else if (row.status === 3) {
          return '停用'
        }
      }
    },
    formatterSalesType(row, column) {
      if (row.salesType) {
        if (row.salesType === 1) {
          return '供应商代发'
        } else if (row.salesType === 2) {
          return '仓库自发'
        }
      }
    },
    formatterRmb(row, column) {
      if (row.mallCostPrice) {
        return '￥' + row.mallCostPrice
      }
    },

    getPurchaseItemist() {
      this.listLoading = true

      this.listQuery.pageNumber =
        (this.listQuery.page - 1) * this.listQuery.pageSize

      var data = {
        offset: this.listQuery.pageNumber,
        count: this.listQuery.pageSize
      }

      if (this.selectWarehouseValue != null) {
        data.warehouseId = this.selectWarehouseValue
      }

      if (this.selectStatusValue != null) {
        data.status = this.selectStatusValue
      }

      if (this.createTimeInterval && this.createTimeInterval.length > 0) {
        // console.log(parseTime(this.createTimeInterval[0]))
        // data.starTime = parseTime(this.createTimeInterval[0]);
        // data.endTime = parseTime(this.createTimeInterval[1]);

        data.starTime = this.createTimeInterval[0].getTime()
        data.endTime = this.createTimeInterval[1].getTime()
      }

      if (this.search != null) {
        data.keyword = this.search
      }

      get('/wxh-cloud-rest/rest/', '/pas/purchaseItem/list', data)
        .then(response => {
          if (response.data.status === 'success') {
            // console.log('-------------------------------------------------------------')
            this.total = response.data.data.purchaseItemCount
            this.purchaseItemList = response.data.data.purchaseItemList

            // console.log(this.skuList)
            this.listLoading = false
          } else if (response.data.status === 'token_check_faild') {
            this.$message({
              message: response.data.messge,
              type: 'warning'
            })
            this.listLoading = false
          }
        })
        .catch(error => {
          console.log(error)
          this.$message({
            message: '数据加载失败',
            type: 'warning'
          })
          this.listLoading = false
        })
    },

    getWarehouseList() {
      var data = { deteleFlag: 'N', 'offset': 0 }

      get('/wxh-cloud-rest/rest/', '/pas/warehouse/queryAllWarehouse', data)
        .then(response => {
          if (response.data.status === 'success') {
            this.warehouseList = response.data.data.list
          } else if (response.data.status === 'token_check_faild') {
            message(this, response.data.messge)
          }
        })
        .catch(error => {
          console.log(error)
          message(this, '数据加载失败')
        })
    },

    selectSort(event) {
      this.selectSortValue = event
      this.listQuery.page = 1
      this.getPurchaseItemist()
    },
    selectStatus(event) {
      this.selectStatusValue = event
      this.listQuery.page = 1
      this.getPurchaseItemist()
    },
    selectWarehouseValues(event) {
      // this.selectWarehouseValue = event
      this.listQuery.page = 1
      this.getPurchaseItemist()
    },

    searchSku(event) {
      // console.log(event)
      this.listQuery.page = 1
      this.getPurchaseItemist()
      // this.getSkuList()
    },

    // 查询分销商
    getDistributorList() {
      distributorList().then(response => {
        this.disList = response.data.data
      })
    },
    handleSizeChange(val) {
      this.listQuery.pageSize = val
      this.getPurchaseItemist()
    },
    handleCurrentChange(val) {
      this.listQuery.page = val
      this.getPurchaseItemist()
    },

    addFun() {
      if (
        this.selectPurchaseItemList &&
        this.selectPurchaseItemList.length > 0
      ) {
        this.selectPurchaseItemList = this.selectPurchaseItemList.map(
          purchaseItem => {
            if (purchaseItem) {
              // var pendingReceiptAmount = 0;
              purchaseItem.amount =
                purchaseItem.amount !== null ? purchaseItem.amount : 0
              purchaseItem.collectAmount =
                purchaseItem.collectAmount !== null
                  ? purchaseItem.collectAmount
                  : 0
              purchaseItem.pendingReceiptAmount =
                purchaseItem.amount - purchaseItem.collectAmount
              return purchaseItem
            }
          }
        )
        this.modalData = {
          type: 'creat',
          title: '采购收货',
          selectPurchaseItemList: this.selectPurchaseItemList
        }
        this.modal = Received
      } else {
        this.$message({
          message: '请选择需要收货的采购项',
          type: 'warning'
        })
      }
    },
    edictFun(data) {
      var sku = data.row
      this.modalData = { type: 'edict', title: '修改sku', sku }
      this.modal = Received
    },
    closeChild() {
      this.modal = null
    },
    closeChildAndRefresh() {
      this.modal = null
      this.listQuery.page = 1
      this.getPurchaseItemist()
    },

    handleSelectionChange(val) {
      console.log(val)
      this.selectPurchaseItemList = val
    },

    getPermission() {
      var arr = document.cookie.split('; ') // 这里显示的格式需要切割一下自己可输出看下

      for (var i = 0; i < arr.length; i++) {
        var arr2 = arr[i].split('=') // 再次切割
        // 判断查找相对应的值
        if (arr2[0] === 'sidebarStatus') {
          this.userid = arr2[1]
        }
      }

      if (localStorage.getItem(this.userid)) {
        return
      }

      getUserInfo().then(response => {
        if (response.data.status === 'ok') {
          localStorage.setItem(
            this.userid,
            JSON.stringify(response.data.data.permissions)
          )
        }
      })
    },

    checkPermission(value) {
      if (value) {
        if (localStorage.getItem(this.userid) && localStorage.getItem(this.userid).indexOf(value) >= 0) {
          return true
        } else {
          return false
        }
      } else {
        return false
      }
    },
    isRowDisable(row) {
      if (row) {
        if (row.status && row.status === 2) {
          if (!row.warehouseName || row.warehouseName !== '中转仓' || row.delivery === 2) {
            return true
          }
        }
      }
      return false
    }
  }
}
</script>
<style>
   body{
     background-color: #ffffff;
   }
    /*表格头部颜色*/
  .el-table__header thead  tr th{
      background-color: #edf4f9;
  }
  /*表格字体*/
  .el-table tr {
      font-size: 10px;
  }
  /*表格行高*/
  .el-table .cell{
    line-height: 1.2;
  }
  /* 用来设置当前页面element全局table 选中某行时的背景色*/
  .el-table__body tr.current-row>td{
     background-color: #D7FFD7 !important;
    /* color: #f19944; */  /* 设置文字颜色，可以选择不设置 */
  }
  .el-table--enable-row-hover .el-table__body tr:hover>td {
    background-color: #D7FFD7;
    /* color: #f19944; */ /* 设置文字颜色，可以选择不设置 */
  }

</style>
